package core.time;

import java.util.PriorityQueue;

import core.WizardsController;
import core.instruction.Action;

public class Timer implements Runnable{

	public static final long TIMER_RESOLUTION_MS = 50;

	private PriorityQueue<TimeAction> pq = new PriorityQueue<TimeAction>();
	private WizardsController controller;

	public Timer(WizardsController wc){
		controller = wc;
	}


	@Override
	public void run() {
		synchronized(this){
			if(!pq.isEmpty()){
				TimeAction next = pq.peek();
				long timeToSleep = (next.gt.toMilliseconds());
				if(timeToSleep < TIMER_RESOLUTION_MS){
					pq.poll();
					controller.instruct(next.a);
				}else{
					try {
						this.wait(timeToSleep);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}else{
				try {
					this.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	public synchronized void doActionAfterTimeT(Action a, GameTime t){
		synchronized(this){
			TimeAction ta = new TimeAction(a, t);
			pq.add(ta);
			this.notify();
		}

	}

	private class TimeAction implements Comparable<TimeAction>{


		Action a;
		GameTime gt;

		TimeAction(Action action, GameTime gametime){
			a = action;
			gt = gametime;
		}

		@Override
		public int compareTo(TimeAction arg0) {
			return this.gt.compareTo(arg0.gt);
		}

	}
}
